package gps.monitor.jt809server.service;

import gps.monitor.common.core.network.ISocketServer;
import gps.monitor.common.core.network.NetworkException;
import gps.monitor.common.tools.network.SimpleNettyConnectConfig;
import gps.monitor.common.tools.network.SocketConnectorFactory;
import gps.monitor.jt809server.network.netty.SimpleJt809NettyDecoder;
import gps.monitor.jt809server.network.netty.SimpleJt809NettyHandler;
import gps.monitor.jt809server.protocol.Jt809Keywords;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 作为上级平台服务器的管理类
 * @author cyq
 * @date 2021/11/5
 * @desc talk is cheep,show me the code
 */
public class UpConnectService {

    @Autowired
    private SimpleJt809NettyHandler simpleJt809NettyHandler;

    public boolean start(int port) {
        try {
            ByteBuf delimiter = Unpooled.buffer(1);
            delimiter.writeByte(Jt809Keywords.K5D);
            DelimiterBasedFrameDecoder decoder = new DelimiterBasedFrameDecoder(2000, false , delimiter);

            ISocketServer server = SocketConnectorFactory.createOneServer(
                    SimpleNettyConnectConfig.serverConfig(port),
                    decoder, //new SimpleJt809NettyDecoder()
                    simpleJt809NettyHandler);
            server.start();
        } catch (NetworkException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
